package com.adnaan.admin.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.adnaan.admin.model.entity.SysUser;
import com.adnaan.admin.service.SysUserService;
import com.adnaan.common.model.Result;
import com.adnaan.common.utils.PasswordUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 系统用户管理控制器
 */
@Tag(name = "系统用户管理", description = "系统用户管理接口")
@RestController
@RequestMapping("/admin/system/user")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService sysUserService;

    /**
     * 分页查询用户列表
     */
    @Operation(summary = "分页查询用户列表", description = "分页查询系统用户列表")
    @SaCheckPermission("system:user:list")
    @GetMapping("/list")
    public Result<IPage<SysUser>> list(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "nickname", required = false) String nickname,
            @RequestParam(value = "status", required = false) Integer status) {

        // 构建查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(username), SysUser::getUsername, username)
                .like(StringUtils.hasText(nickname), SysUser::getNickname, nickname)
                .eq(status != null, SysUser::getStatus, status)
                .orderByDesc(SysUser::getCreateTime);

        // 执行分页查询
        IPage<SysUser> page = sysUserService.page(new Page<>(pageNum, pageSize), queryWrapper);

        return Result.success(page);
    }

    /**
     * 获取用户详情
     */
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详情")
    @SaCheckPermission("system:user:query")
    @GetMapping("/{id}")
    public Result<SysUser> getInfo(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    /**
     * 添加用户
     */
    @Operation(summary = "添加用户", description = "添加系统用户")
    @SaCheckPermission("system:user:add")
    @PostMapping
    public Result<Void> add(@RequestBody SysUser user) {
        // 校验用户名是否已存在
        SysUser existUser = sysUserService.getByUsername(user.getUsername());
        if (existUser != null) {
            return Result.error("用户名已存在");
        }

        // 设置密码
        user.setPassword(PasswordUtil.encode(user.getPassword()));

        // 保存用户
        sysUserService.save(user);

        // 如果有角色，分配角色
        if (user.getRoleIds() != null && user.getRoleIds().length > 0) {
            // 角色分配逻辑可在后续实现
        }

        return Result.success();
    }

    /**
     * 修改用户
     */
    @Operation(summary = "修改用户", description = "修改系统用户")
    @SaCheckPermission("system:user:edit")
    @PutMapping
    public Result<Void> update(@RequestBody SysUser user) {
        // 校验用户是否存在
        SysUser existUser = sysUserService.getById(user.getId());
        if (existUser == null) {
            return Result.error("用户不存在");
        }

        // 更新用户信息
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(PasswordUtil.encode(user.getPassword()));
        } else {
            user.setPassword(null); // 不更新密码
        }

        sysUserService.updateById(user);

        // 如果有角色，更新角色
        if (user.getRoleIds() != null && user.getRoleIds().length > 0) {
            // 角色更新逻辑可在后续实现
        }

        return Result.success();
    }

    /**
     * 删除用户
     */
    @Operation(summary = "删除用户", description = "删除系统用户")
    @SaCheckPermission("system:user:remove")
    @DeleteMapping("/{ids}")
    public Result<Void> remove(@PathVariable Long[] ids) {
        // 防止删除自身
        Long currentUserId = cn.dev33.satoken.stp.StpUtil.getLoginIdAsLong();
        if (Arrays.asList(ids).contains(currentUserId)) {
            return Result.error("不能删除当前登录用户");
        }

        // 删除用户
        List<Long> idList = Arrays.asList(ids);
        sysUserService.removeByIds(idList);

        return Result.success();
    }

    /**
     * 重置密码
     */
    @Operation(summary = "重置密码", description = "重置用户密码")
    @SaCheckPermission("system:user:edit")
    @PutMapping("/resetPwd")
    public Result<Void> resetPwd(@RequestBody SysUser user) {
        // 校验用户是否存在
        SysUser existUser = sysUserService.getById(user.getId());
        if (existUser == null) {
            return Result.error("用户不存在");
        }

        // 修改密码
        SysUser updateUser = new SysUser();
        updateUser.setId(user.getId());
        updateUser.setPassword(PasswordUtil.encode(user.getPassword()));

        sysUserService.updateById(updateUser);

        return Result.success();
    }

    /**
     * 修改用户状态
     */
    @Operation(summary = "修改用户状态", description = "启用/禁用用户")
    @SaCheckPermission("system:user:edit")
    @PutMapping("/changeStatus")
    public Result<Void> changeStatus(@RequestBody SysUser user) {
        // 防止修改自身状态
        Long currentUserId = cn.dev33.satoken.stp.StpUtil.getLoginIdAsLong();
        if (user.getId().equals(currentUserId)) {
            return Result.error("不能修改当前登录用户状态");
        }

        // 修改状态
        SysUser updateUser = new SysUser();
        updateUser.setId(user.getId());
        updateUser.setStatus(user.getStatus());

        sysUserService.updateById(updateUser);

        return Result.success();
    }
} 